/* eslint-disable new-cap */
import eventBus from './eventbus'

let _map = null
const _typeNameMap = new Map()
let _sgLayer = null
let featureLayer, featureCache
let _circleLayer = null
let _clusterLayer = null
let _locationLayer = null

let directionsTask = null
let geocoderTask = null
export default {
  getMap: function () {
    return _map
  },
  setMap: function (map) {
    _map = map
  },
  setTypeNames: function (typeNames) {
    _typeNameMap.clear()
    for (const val of typeNames) {
      _typeNameMap.set(val.typeid, val)
    }
  },
  getTypeNames: function () {
    return Array.from(_typeNameMap.values())
  },
  setSgLayer: function (sgLayer) {
    _sgLayer = sgLayer
    // const _this = this
    // 因为没有回调，暂时使用延时处理
    // setTimeout(() => {
    //     if (SGMap){
    //         _this.initSgTask();
    //     }
    // }, 7 * 1000);
  },
  initSgTask () {
    // eslint-disable-next-line no-undef
    SGMap.plugin(['SGMap.GeocoderTask', 'SGMap.DirectionsTask']).then(function (res) {
      // eslint-disable-next-line no-undef
      directionsTask = new SGMap.DirectionsTask()
      // eslint-disable-next-line no-undef
      geocoderTask = new SGMap.GeocoderTask()
    })
  },
  getDirectionTask () {
    return directionsTask
  },
  getDeocoderTask () {
    return geocoderTask
  },
  getSgLayer: function () {
    return _sgLayer
  },
  setFeatureCacheLayer (cache, layer) {
    featureCache = cache
    featureLayer = layer
  },
  getFeatureCache () {
    return featureCache
  },
  getFeatureLayer () {
    return featureLayer
  },
  setCircleLayer (circleLayer) {
    _circleLayer = circleLayer
  },
  getCircleLayer () {
    return _circleLayer
  },
  // #region 1. 功能工具类方法
  // 获取显示比例范围
  getZoomResolutions () {
    const maxSize = 156543.03392
    const zoomCount = 26
    const zoomResolutions = []
    for (let i = 0; i < zoomCount; i++) {
      zoomResolutions.push(maxSize / Math.pow(2, i))
    }
    return zoomResolutions
  },
  // 经纬度转换为屏幕像素
  geoCoord2Pixel: function (geoCoord) {
    // eslint-disable-next-line no-undef
    var point = new L.latLng(geoCoord[1], geoCoord[0])
    var pos = _map.latLngToContainerPoint(point)
    return [pos.x, pos.y]
  },
  // 屏幕像素转换为经纬度
  pixel2GeoCoord: function (pixel) {
    // eslint-disable-next-line no-undef
    var point = _map.containerPointToLatLng(L.point(pixel[0], pixel[1]))
    return [point.lng, point.lat]
  },
  invalidateContainer (time) {
    setTimeout(() => {
      _map.invalidateSize(true)
    }, time)
  },
  // 距离计算保留整数
  getDistance (arr1, arr2) {
    const distance = _map.getDistance(arr1, arr2)
    return Math.floor(distance * 100) / 100
  },
  // 经纬度转墨卡托，处理字符串
  lngLat2Mercator (latLngArr) {
    // eslint-disable-next-line no-undef
    const mercatorObj = egis.tool.Util.projectLngLatToWebMercator(Number(latLngArr[0]), Number(latLngArr[1]))
    return [mercatorObj.x, mercatorObj.y]
  },
  getMapCenterArr () {
    const mapCenterObj = _map.getMapCenter()
    return [mapCenterObj.x, mapCenterObj.y]
  },
  // 切换卫星图
  switchSgMapSatellite (isSate) {
    _sgLayer.changeSatelliteLayer(isSate)
  },
  // #endregion

  // #region 2. 业务工具类相关
  // 获取设备的shape，如果当前shape不存在，则取父级shape
  getShapeObj (device) {
    if (device.shape) {
      return device.shape
    }
    return device.parentDevice.shape
  },

  // 获取shape的中心点，通常用于跳转
  getShapeCenter (shapeStr, isObj) {
    let shapeObj
    if (isObj) {
      shapeObj = shapeStr
    } else {
      shapeObj = JSON.parse(shapeStr)
    }
    if (shapeObj.type === 'Point') {
      return shapeObj.coordinates
    } else if (shapeObj.type === 'LineString') {
      return shapeObj.coordinates[1]
    } else if (shapeObj.type === 'Polygon') {
      return shapeObj.coordinates[0][1]
    }
    return []
  },

  // 根据 [oid] 转换成服务请求格式 oid in ()
  transformOidStrByFeature (features) {
    let str = 'oid in ('
    for (const feature of features) {
      str += Number(feature.oid) + ','
    }
    str = str.substr(0, str.length - 1) + ')'
    return str
  },

  // 获取设备类型定义信息
  getTypeName (layerId) {
    if (_typeNameMap.size > 0) {
      return _typeNameMap.get(layerId).typealias
    } else {
      return '类型未定义'
    }
  },

  // 转义信息转换
  getCodeObj (fieldList, keys) {
    const resultObj = {}
    for (const fieldObj of fieldList) {
      if (keys.indexOf(fieldObj.fieldName) > -1) {
        resultObj[fieldObj.fieldName + 'Name'] = fieldObj.transferredValue || fieldObj.codeValue
        resultObj[fieldObj.fieldName] = fieldObj.codeValue
      }
    }
    return resultObj
  },

  // 获取有值的数据展示

  // #endregion

  // #region 3. 业务功能-跟随地图圈展示
  // 根据圆形，创建边界
  createExtentByCircle (circleGraph) {
    const center = circleGraph.getGeometry().getCenter()
    const radius = Number(circleGraph.getGeometry().getRadius())
    const leftBottom = [center.x - radius, center.y - radius]
    const rightTop = [center.x + radius, center.y + radius]
    // eslint-disable-next-line no-undef
    return new egis.geometry.Extent(leftBottom[0], leftBottom[1], rightTop[0], rightTop[1])
  },
  // 地图图层不展示
  layerNotShow () {
    featureLayer.removeFrom(_map)

    // let mapExtent = _map.getExtent();
    // featureLayer.updateCacheData({
    //     // extent 传参是左上角，右下角
    //     // 转换的服务 传参是，左下角，右上角
    //     customExtent: mapExtent,
    //     customSize: new L.point(0, 0),
    // });
  },
  // 根据限定范围矢量电网
  showFeatureByArea () {
    // drawPolygon.on('draw.Polygon.start', function () {
    //   console.log('draw.Polygon.start')
    // })
    // 1、判断是否选中选定区域，不选中则不展示
    if (!_circleLayer || _circleLayer.getGraphics().length === 0) {
      this.layerNotShow()
      return
    }

    // 2、根据circleLayer转换矩形
    const mapExtent = _map.getExtent()
    const circleGraph = _circleLayer.getGraphics()[0]
    const extent = this.createExtentByCircle(circleGraph)

    // 3. 判断是否相交，不相交则宽高设为0
    const isIntersection = mapExtent.intersectsAndDoesNotTouch(extent)
    if (!isIntersection) {
      this.layerNotShow()
      return
    }

    // 4. 部分相交或全包含，计算可视范围与限定范围的交集，计算宽高
    featureLayer.addTo(_map)
    const intersection = mapExtent.intersection(extent)

    // 实际宽高为交集部分左上角和右下角位置
    const topLeft = this.geoCoord2Pixel([intersection.getXmin(), intersection.getYmax()])
    const rightBottom = this.geoCoord2Pixel([intersection.getXmax(), intersection.getYmin()])
    const width = Math.ceil(Math.abs(topLeft[0] - rightBottom[0]))
    const height = Math.ceil(Math.abs(topLeft[1] - rightBottom[1]))
    // eslint-disable-next-line no-undef
    const point = new L.point(width, height)

    setTimeout(() => {
      featureLayer.updateCacheData({
        // extent 传参是左上角，右下角
        // 转换的服务 传参是，左下角，右上角
        customExtent: intersection,
        customSize: point
      })
    }, 5)
  },

  // 添加聚类图层marker点
  // 收集变压器坐标并绘制
  showClusterLayer (features) {
    // 存在即更新，否则新增
    if (_clusterLayer) {
      _clusterLayer.clearMarkers()
    } else {
      // eslint-disable-next-line no-undef
      _clusterLayer = egis.layer.clusterLayer()// 创建聚类图层
      _map.addLayer(_clusterLayer)// 地图上添加聚类图层
    }

    for (const feature of features) {
      const mecArr = this.getShapeCenter(feature.shape, true)

      if (mecArr && mecArr.length > 0) {
        _clusterLayer.addMarker(this.createSectionMarker(mecArr, feature))
      }
    }
  },
  // 绘制变压器标识marker
  createSectionMarker (mercatorArray, feature) {
    // eslint-disable-next-line no-undef
    const myIcon = egis.overlay.icon({
      // iconUrl: require('@/assets/images/markers_blue.png'),
      iconSize: [25, 39],
      iconAnchor: [12.5, 39],
      popupAnchor: [0, -40]
    })

    // No.2 添加marker及事件
    // eslint-disable-next-line no-undef
    const marker = new egis.overlay.Marker(mercatorArray, {
      icon: myIcon
    })

    // if (!isMobileRoute()) {
    //   // let popup = new egis.overlay.Popup({
    //   //     closeOnClick: false,
    //   //     closeButton: false
    //   // });
    //   //
    //   // let htmlStr = "直线距离[M]：" + feature.zxjl +
    //   //     "<br>可开放容量[kVA]：" + 500 +
    //   //     "<br>负载率：" + '55%';
    //   // popup.setContent(htmlStr);
    //   // marker.bindPopup(popup, {keepInView: false, autoClose: false});
    //   //
    //   // marker.on("mouseover", e => {
    //   //     e.target.openPopup();
    //   // });
    //   // marker.on("mouseout", e => {
    //   //     e.target.closePopup();
    //   // });
    // }

    marker.on('click', e => {
      // eslint-disable-next-line no-undef
      const geometry = new egis.geometry.Point(e.latlng.lng, e.latlng.lat)
      _map.flyCenter(geometry)

      eventBus.$emit('showAttrListByMap', feature)
    })

    return marker
  },

  // 点击地图跳转展示
  onMapFlyRound (centerArr, radius) {
    const centerX = centerArr[0]
    const centerY = centerArr[1]
    const leftTop = [centerX - radius, centerY + radius]
    const rightTop = [centerX + radius, centerY + radius]
    const leftBottom = [centerX - radius, centerY - radius]
    const rightBottom = [centerX + radius, centerY - radius]
    _map.flyExtent([leftTop, rightTop, leftBottom, rightBottom])
  },
  // #endregion

  // 在指定位置添加一个marker
  addMarker (mercatorArray) {
    // eslint-disable-next-line no-undef
    const myIcon = egis.overlay.icon({
      // iconUrl: require('@/assets/images/markers_blue.png'),
      iconSize: [25, 39],
      iconAnchor: [12.5, 39]
      // popupAnchor: [0, -40]
    })

    // No.2 添加marker及事件
    // eslint-disable-next-line no-undef
    const marker = new egis.overlay.Marker(mercatorArray, {
      icon: myIcon
    })

    _map.addLayer(marker)

    return marker
  },

  // 设置定位蓝圈点
  setLocationLayer (centerArr, radius) {
    // 有则更新
    if (_locationLayer) {
      const graphic = _locationLayer.getGraphics()[0]

      graphic.getGeometry().setX(centerArr[0])
      graphic.getGeometry().setY(centerArr[1])
    } else {
      // eslint-disable-next-line no-undef
      _locationLayer = new egis.layer.GraphicsLayer()
      // eslint-disable-next-line no-undef
      const geometry = new egis.geometry.Point(centerArr[0], centerArr[1])
      // eslint-disable-next-line no-undef
      const symbol = new egis.symbol.SimpleMarkerSymbol({
        scale: 1,
        color: '#3477ff',
        offset: [0, 0],
        opacity: 1,
        // isCache: true,
        stroke: true,
        size: 18,
        outline: {
          color: '#FFFFFF',
          width: 2
        },
        symbolStyle: 'circle'
      })
      // eslint-disable-next-line no-undef
      const graphic = new egis.Graphic({ geometry: geometry, symbol: symbol })
      _locationLayer.addTo(_map)
      _locationLayer.addGraphic(graphic)
    }
  }
}
